import {Button} from "antd"
import {memo, useCallback, useEffect, useState} from "react"
import classNames from "classnames"
import "./index.less"


export interface INavItem {
    key: string,
    label: React.ReactElement | string | undefined
}

export const NavTabs = memo((
    props: {
        options: INavItem[],
        defaultValue?: string,
        value?: string,
        onChange: (value: string) => void
    }
) => {
    const {defaultValue, value, options, onChange} = props
    const [inputValue, setInputValue] = useState<string | undefined>(defaultValue || value || props.options?.[0]?.key)

    useEffect(() => {
        setInputValue(value)
    }, [value])

    const handleItemClick = useCallback((key: string) => {
        setInputValue(key)
        onChange?.(key)
    }, [onChange])

    return (
        <div className="nav-tabs">
            {
                options?.map((option, index) => {
                    return (
                        <Button
                            key={option.key}
                            type={option.key === inputValue ? "link" : "text"}
                            onClick={() => handleItemClick(option.key)}
                        >
                            <div
                                role="img"
                                className={classNames("nav-icon", "ant-icon", option.key === inputValue ? "selected" : undefined)}
                            >
                                {index + 1}
                            </div>
                            {option.label}
                        </Button>
                    )
                })
            }
        </div>
    )
})
